﻿using IOA.MES.Business;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using NLog;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace IOA.MES.Web.Controllers
{
    /// <summary>
    /// 计划管理
    /// </summary>
    public class PlanController : Controller
    {
        private Logger logger = LogManager.GetLogger(nameof(PlanController));

        #region 订单管理
        /// <summary>
        /// 订单管理
        /// </summary>
        public ActionResult OrderMgr()
        {
            return View();
        }

        /// <summary>
        /// 查询订单列表
        /// </summary>
        public JsonResult QueryOrders(int page, int limit, string orderNo, string customer, OrderStatus? status, DateTime? startDate, DateTime? endDate)
        {
            var total = 0;
            var orders = new OrderMgr().QueryOrders(page, limit, out total, orderNo, customer, status, startDate, endDate);
            return Json(new ResultJson<object>(orders, total));
        }

        /// <summary>
        /// 编辑订单页面
        /// </summary>
        public ActionResult EditOrder(int orderId)
        {
            var order = orderId <= 0 ? new VOrder { OrderTime = DateTime.Now } : new OrderMgr().GetOrder(orderId);
            return View(order);
        }

        /// <summary>
        /// 编辑订单接口
        /// </summary>
        [HttpPost]
        public JsonResult EditOrder(VOrder model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new OrderMgr().EditOrder(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 工单管理
        /// <summary>
        /// 工单管理
        /// </summary>
        public ActionResult WorkOrderMgr(string orderNo)
        {
            ViewBag.OrderNo = orderNo ?? string.Empty; ;
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.WorkOrderStatusEnums = new CommonMgr().QueryEnumTypes(typeof(ProduceStatus));
            return View();
        }

        /// <summary>
        /// 创建工单
        /// </summary>
        public ActionResult CreateWorkOrder(string workOrderNo = "")
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            var workOrder = string.IsNullOrWhiteSpace(workOrderNo) ? null : new WorkOrderMgr().GetWorkOrderWithBoms(workOrderNo);
            return View(workOrder);
        }

        /// <summary>
        /// 创建工单
        /// </summary>
        [HttpPost]
        public JsonResult CreateWorkOrder(VWorkOrder workOrder)
        {
            try
            {
                workOrder.InnerOrderNo = workOrder.OrderNo;
                new WorkOrderMgr().AsyncWorkOrder(new List<VWorkOrder> { workOrder });
            }
            catch (BizException ex)
            {
                return Json(new { ErrCode = ex.ErrCode, ErrMsg = ex.Message });
            }
            catch (Exception ex)
            {
                return Json(new { ErrCode = 500, ErrMsg = ex.Message });
            }
            return Json(new { ErrCode = 200, Data = "", TotalCount = 0 });
        }

        /// <summary>
        /// 编辑工单页面
        /// </summary>
        public ActionResult EditWorkOrder(string workOrderNo)
        {
            var paras = new CellParaMgr().QueryParas(null);
            ViewBag.CellLevelParas = paras.Where(_ => _.ParaType == ParaType.CellLevel).OrderBy(_ => _.ParaValue).ToList();
            ViewBag.CellModelParas = paras.Where(_ => _.ParaType == ParaType.CellModel).OrderBy(_ => _.ParaValue).ToList();
            ViewBag.CellEfficiencyParas = paras.Where(_ => _.ParaType == ParaType.CellEfficiency).OrderBy(_ => _.ParaValue).ToList();
            ViewBag.OutputPowerParas = paras.Where(_ => _.ParaType == ParaType.OutputPower).OrderBy(_ => _.ParaValue).ToList();
            ViewBag.SingleCellPowerParas = paras.Where(_ => _.ParaType == ParaType.SinglePower).OrderBy(_ => _.ParaValue).ToList();
            var workOrder = new WorkOrderMgr().GetWorkOrder(workOrderNo);
            ViewBag.BinningPowers = new BinningSchemeMgr().QueryNameplateModels(workOrder.WorkshopCode);

            return View(workOrder);
        }

        /// <summary>
        /// 获取功率档对象
        /// </summary>
        [HttpPost]
        public JsonResult GetBinnningPower(int powerId)
        {
            var power = new BinningSchemeMgr().GetBinningPower(powerId);
            return Json(new ResultJson<object>(power));
        }

        /// <summary>
        /// 编辑工单接口
        /// </summary>
        [HttpPost]
        public JsonResult EditWorkOrder(VWorkOrder model)
        {
            model.ModifyBy = BaseEnv.UserId;
            model.QLevels = model.QLevels.Where(_ => !string.IsNullOrWhiteSpace(_.ProductCode) && !string.IsNullOrWhiteSpace(_.ProductName)).ToList();
            new WorkOrderMgr().EditWorkOrder(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 组件条码生成
        /// </summary>
        public ActionResult ComponentEdit(string workOrderNo = "")
        {
            var workOrder = new WorkOrderMgr().GetWorkOrder(workOrderNo);
            return View(workOrder);
        }

        /// <summary>
        /// 生成组件条码
        /// </summary>
        [HttpPost]
        public JsonResult CreateComponents(VDistributeTask model, List<string> barCodes = null)
        {
            model.CreateBy = BaseEnv.UserId;
            new ComponentMgr().CreateComponents(model, barCodes);

            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询组件列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryComponents(int page, int limit, string workOrderNo)
        {
            var total = 0;
            var componentts = new ComponentMgr().QueryWorkOrderComponents(page, limit, out total, workOrderNo);

            return Json(new ResultJson<object>(componentts, total));
        }
        #endregion

        #region 返修工单
        /// <summary>
        /// 返修工单管理
        /// </summary>
        public ActionResult ReworkMgr()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            ViewBag.ProcessStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ProduceStatus));
            ViewBag.ReviewStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ReviewStatus)).Where(_ => _.Key != 0).ToList();
            ViewBag.ReworkTypes = new CommonMgr().QueryEnumTypes(typeof(ReworkType));

            return View();
        }

        /// <summary>
        /// 查询返修单列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryReworks(int page, int limit, string orderNo, string reworkNo, string workshopCode, ProduceStatus? produceStatus, ReworkType? reworkType, DateTime? startDate, DateTime? endDate)
        {
            var total = 0;
            var models = new ReworkMgr().QueryPlanReworks(page, limit, out total, orderNo, reworkNo, workshopCode, null, produceStatus, reworkType, startDate, endDate?.AddDays(1));
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 返工详情
        /// </summary>
        /// <returns></returns>
        public ActionResult ReworkDetail(string reworkNo)
        {
            ViewBag.ReviewStatusEnum = new CommonMgr().QueryEnumTypes(typeof(ReviewStatus));
            var model = new ReworkMgr().GetRework(reworkNo);
            return View(model);
        }

        /// <summary>
        /// 获取返工单
        /// </summary>
        [HttpPost]
        public JsonResult GetRework(string reworkNo)
        {
            var model = new ReworkMgr().GetRework(reworkNo);
            return Json(new ResultJson<object>(model));
        }


        /// <summary>
        /// 审核返工工单
        /// </summary>
        [HttpPost]
        public JsonResult ReviewRework(VReworkOrder model)
        {
            model.ReviewBy = BaseEnv.UserId;
            model.ModifyBy = BaseEnv.UserId;
            new ReworkMgr().ReviewRework(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 调拨单
        /// <summary>
        /// 调拨管理页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AllocateOrderMgr(string workOrderNo)
        {
            ViewBag.WorkOrderNo = workOrderNo ?? string.Empty;
            return View();
        }

        /// <summary>
        /// 查询订单列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryAllocateOrders(int page, int limit, string toWarehouseCode, string workOrderNo, string allocateNo, DateTime? startDate, DateTime? endDate)
        {
            var total = 0;
            var orders = new AllocateOrderMgr().QueryAllocateOrders(page, limit, out total, toWarehouseCode, workOrderNo, allocateNo, null, startDate, !endDate.HasValue ? (DateTime?)null : endDate.Value.AddDays(1));
            return Json(new ResultJson<object>(orders, total));
        }

        /// <summary>
        /// 调拨详情页
        /// </summary>
        public ActionResult AllocateOrderDetail(string allocateNo)
        {
            var entity = new AllocateOrderMgr().GetAllocateOrder(allocateNo);
            return View(entity);
        }

        /// <summary>
        /// 获取所有调拨物料
        /// </summary>
        [HttpPost]
        public JsonResult QueryAllocateProducts(int page, int limit, string allocateNo = "")
        {
            if (!string.IsNullOrWhiteSpace(allocateNo))
            {
                var total = 0;
                var products = new AllocateOrderMgr().QueryAllocateProducts(page, limit, out total, allocateNo);
                return Json(new ResultJson<object>(products, total));
            }
            else
            {
                return Json(new ResultJson<object>());
            }
        }

        /// <summary>
        /// 创建调拨单
        /// </summary>
        public ActionResult EditAllocateOrder(string allocateNo = "")
        {
            ViewBag.Warehouses = new WarehouseMgr().QueryWarehouses();
            var model = string.IsNullOrWhiteSpace(allocateNo) ? null : new AllocateOrderMgr().GetAllocateOrder(allocateNo);
            return View(model);
        }

        /// <summary>
        /// 保存调拨单
        /// </summary>
        [HttpPost]
        public JsonResult SaveAllocate(VAllocateOrder model)
        {
            model.CreateBy = BaseEnv.UserId;
            model.ModifyBy = BaseEnv.UserId;
            model = new AllocateOrderMgr().SaveAllocateOrder(model);

            return Json(new ResultJson<VAllocateOrder>(model));
        }

        /// <summary>
        /// 获取调拨物料列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryAllocateProductList(string allocateNo)
        {
            var data = new AllocateOrderMgr().QueryAllocateProductList(allocateNo);
            return Json(new ResultJson<List<VAllocateProduct>>(data));
        }

        /// <summary>
        /// 保存调拨物料
        /// </summary>
        [HttpPost]
        public JsonResult SaveAllocateProducts(string allocateNo, List<VAllocateProduct> products)
        {
            new AllocateOrderMgr().SaveAllocateProducts(BaseEnv.UserId, allocateNo, products ?? new List<VAllocateProduct>());
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 审核调拨单
        /// </summary>
        public JsonResult ReviewAllocateOrder(string allocateNo)
        {
            new AllocateOrderMgr().ReviewAllocateOrder(BaseEnv.UserId, allocateNo);

            return Json(new ResultJson<object>());
        }
        #endregion

        #region 发货单管理
        /// <summary>
        /// 发货单管理
        /// </summary>
        public ActionResult DeliveryOrderMgr()
        {
            ViewBag.Warehouses = new WarehouseMgr().QueryWarehouses(WarehouseType.Product, string.Empty, CommonStatus.Normal);
            return View();
        }

        /// <summary>
        /// 查询发货单
        /// </summary>
        [HttpPost]
        public JsonResult QueryDeliveryOrders(int page, int limit, string warehouseCode, string deliveryOrderNo, string orderNo, string customer, DateTime startDate, DateTime endDate)
        {
            var total = 0;
            var orders = new DeliveryMgr().QueryDeliveryOrders(page, limit, out total, warehouseCode, deliveryOrderNo, orderNo, customer, startDate, endDate);

            return Json(new { ErrCode = 200, Data = orders, TotalCount = total });
        }

        /// <summary>
        /// 发货单编辑
        /// </summary>
        public ActionResult DeliveryEdit(string deliveryNo)
        {
            ViewBag.Warehouses = new WarehouseMgr().QueryWarehouses(WarehouseType.Product, string.Empty, CommonStatus.Normal);
            var deliveryOrder = new DeliveryMgr().GetDelivery(deliveryNo);
            return View(deliveryOrder);
        }

        /// <summary>
        /// 保存发货单
        /// </summary>
        [HttpPost]
        public JsonResult SaveDelivery(VDeliveryOrder model)
        {
            if (string.IsNullOrWhiteSpace(model.DeliveryNo))
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new DeliveryMgr().SaveDelivery(model);
            return Json(new { ErrCode = 200 });
        }

        /// <summary>
        /// 发货单详情
        /// </summary>
        public ActionResult DeliveryDetail(string deliveryNo)
        {
            var deliveryOrder = new DeliveryMgr().GetDelivery(deliveryNo);
            return View(deliveryOrder);
        }

        /// <summary>
        /// 发货柜号编辑管理
        /// </summary>
        public ActionResult EditDeliveryCabinets(string deliveryNo)
        {
            var deliveryOrder = string.IsNullOrWhiteSpace(deliveryNo) ? null : new DeliveryMgr().GetDelivery(deliveryNo);
            return View(deliveryOrder);
        }

        /// <summary>
        /// 发货柜号编辑管理
        /// </summary>
        [HttpPost]
        public JsonResult UploadDeliveryCabinets()
        {
            if (Request.Files.Count <= 0)
            {
                return Json(new ResultJson<object>(500, "上传的文件为空"));
            }

            var file = Request.Files[0];
            try
            {
                file.InputStream.Position = 0;
                IWorkbook wk = null;
                if (file.FileName.EndsWith("xlsx", StringComparison.CurrentCultureIgnoreCase))
                {
                    wk = new XSSFWorkbook(file.InputStream);
                }
                else
                {
                    wk = new HSSFWorkbook(file.InputStream);
                }

                var importItems = new List<string>();
                var sheet = wk.GetSheetAt(0);
                for (int r = 0; r <= sheet.LastRowNum; r++)
                {
                    importItems.Add(Convert.ToString(sheet.GetRow(r).Cells[0])?.Trim());
                }
                return Json(new ResultJson<object>(importItems.Where(_ => !string.IsNullOrWhiteSpace(_)).Select(_ => _.ToUpper().Trim()).Distinct().ToList()));
            }
            catch (Exception ex)
            {
                return Json(new ResultJson<object>(500, $"文件读取出错：{ex.ToString()}"));
            }
        }

        /// <summary>
        /// 发货柜号编辑管理
        /// </summary>
        [HttpPost]
        public JsonResult QueryDispatchProducts(string deliveryNo)
        {
            var products = new DeliveryMgr().QueryDeliveryProducts(deliveryNo);
            return Json(new ResultJson<object>(products, products.Count));
        }

        /// <summary>
        /// 发货柜号编辑管理
        /// </summary>
        [HttpPost]
        public JsonResult SaveDeliveryCabinets(string deliveryNo, List<string> cabinetNos)
        {
            new DeliveryMgr().SaveDeliveryCabinets(new VDeliveryOrder
            {
                DeliveryNo = deliveryNo,
                ModifyBy = BaseEnv.UserId,
            }, cabinetNos);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 确认发货
        /// </summary>
        [HttpPost]
        public JsonResult SubmitDelivery(string deliveryNo)
        {
            new DeliveryMgr().SubmitDelivery(new VDeliveryOrder
            {
                DeliveryNo = deliveryNo,
                ModifyBy = BaseEnv.UserId,
            });
            return Json(new ResultJson<object>());
        }
        #endregion
    }
}
